package com.zdw.zfw.admin.core;

import com.zdw.zfw.core.enums.ZfwExceptionInfoEnum;
import com.zdw.zfw.core.http.HttpResult;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局的的异常拦截器
 *
 * @author zdw
 * @date 2019/2/23
 */
@RestControllerAdvice
@Order(-1)
public final class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 无权访问该资源异常
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public HttpResult authorizationException(UnauthorizedException e) {
        log.error(ZfwExceptionInfoEnum.NO_PERMITION.getMessage(), e);
        return HttpResult.error(ZfwExceptionInfoEnum.NO_PERMITION);
    }

    /**
     * 未登录异常
     */
    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public HttpResult unauthenticatedException(UnauthenticatedException e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        log.error(ZfwExceptionInfoEnum.NOT_LOGIN.getMessage(), e);
        return HttpResult.error(ZfwExceptionInfoEnum.NOT_LOGIN);
    }
}
